<?php


namespace app\madmin\service;

use app\madmin\model\Link;
use app\madmin\model\LinkClick;
use app\utils\UrlLink;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Cache;
use think\facade\Db;

class UrlLinkService
{

    public function __construct()
    {

    }

    /**列表
     * @param array $data
     * @return array
     * @throws DbException
     */
    public function list($page, $size)
    {
        global $user;

        $where[] = ['mall_id', '=', $user->mall_id];
        $data = request()->get();
        !empty($data['name']) && $where[] = ['title', 'like', '%' . $data['name'] . '%'];
        !empty($data['status']) && $where[] = ['status', '=', $data['status']];
        !empty($data['start_time']) && $where[] = ['create_time', '>=', $data['start_time']];
        !empty($data['end_time']) && $where[] = ['create_time', '<=', $data['end_time']];

        $res = Link::where($where)->withCount(['click' => 'click'])->order('id', 'desc')->paginate(['page' => $page, 'list_rows' => $size]);
        foreach ($res as $item=>$value){
            if ($value->is_forever==1)$value->status=0;
        }
        return [HTTP_SUCCESS, $res];
    }

    /**详情
     * @param int $id
     * @return int
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     */
    public function detail(int $id)
    {
        $find = Link::find($id);

        $ip = getIp();
        if ($find) {
            $linkClickModel = LinkClick::where(['link_id' => $id, 'ip' => $ip])->find();
            if (empty($linkClickModel)) {
                $data = [
                    'ip' => $ip,
                    'link_id' => $id,
                    'mall_id' => $find->mall_id
                ];
                LinkClick::create($data);
            }

            if ($find->expired_time < date("Y-m-d H:i:s", time()) && $find->is_forever == 1) {
                //过期了自动续费
                list($http, $data) = $this->generate($find);
                if ($http != 200) {
                    return [$http, $find];
                }
                //更新链接
                $find->expired_time = date("Y-m-d H:i:s", strtotime("+30 day"));
                $find->url_link = $data;
                $find->status = 0;
                $find->save();
                return [HTTP_SUCCESS, $find];
            }
            $key="url_link:".$ip."id:".$id;

            if (Cache::get($key)) return [HTTP_SUCCESS, Cache::get($key)];

            #在有效期内每个ip给一个链接
            if($find->expired_time > date("Y-m-d H:i:s", time()) ){

                list($http, $data) = $this->generate($find,1);
                if ($http != 200) {
                    return [$http, $find];
                }
                $find->url_link = $data;
                Cache::set($key,$find,24*60*60);
            }
        }



        return [HTTP_SUCCESS, $find];
    }


    /**添加
     * @param array $data
     * @return array
     */
    public function add()
    {

        global $user;
        list($http, $data) = $this->generate();

        if ($http != 200) {
            return [$http, $data];
        }
        $url_link = request()->post('url_link', '');
        $url_info = parse_url($url_link);

        $query = [
            "mall_id={$user->mall_id}"
        ];
        if (isset($url_info['query'])) {
            $arr = array_values(explode("&", $url_info['query']));
            $query = array_merge($query, $arr);
        }
        $path = implode("&", $query);

        $post = request()->post();
        $url_link = $data;
        $day = $post['day'] ?? 1;
        $day = $day < 0 ? 30 : ($day > 30 ? 30 : $day); //范围只能在1-30天
        $model = new Link();
        $model->title = $post['title'] ?? '';
        $model->mall_id = $user->mall_id;
        $model->url_link = $url_link;
        $model->is_forever = $post['day'] < 0 ? 1 : 0; //天数小于0则为永久
        $model->path = $path;
        $model->wx_url_path = str_replace("..", 'pages', $url_info['path'] ?? '');
        $model->expired_time = date("Y-m-d", strtotime("+$day day"));
        $model->save();

        return [HTTP_SUCCESS, $model];
    }


    /**
     * 删除
     * @param array $data
     * @return array
     * @throws DbException
     */
    public function delete($id)
    {

        $model = Link::find($id);
        if (empty($model)) {
            return [HTTP_NOTACCEPT, '删除失败'];
        }
        $model->delete();
        return [HTTP_SUCCESS, $model];
    }

    public function generate($link=null,$link_day=30)
    {
        if (empty($link)) {
            global $user;
            $url_link = request()->post('url_link', '');
            $day = $post['day'] ?? 1;
            $day = $day < 0 ? 30 : ($day > 30 ? 30 : $day); //范围只能在1-30天
            $url_info = parse_url($url_link);
            $query = [
                "mall_id={$user->mall_id}"
            ];
            if (isset($url_info['query'])) {
                $arr = array_values(explode("&", $url_info['query']));
                $query = array_merge($query, $arr);
            }
            $query = implode("&", $query);

        }

        else{
            $query = $link->path ?? '';
            $url_info['path'] = $link->wx_url_path ?? '';
            $day = $link_day;
            global $user;
            $user = $link;
        }

        $data = [
            'path' => str_replace("..", 'pages', $url_info['path'] ?? ''),
            'query' => $query,
            'expire_type' => 1,
            'expire_interval' => $day,
        ];
        $response = UrlLink::generate_urllink($data);
        if ($response['errcode'] != 0) {
            return [HTTP_NOTACCEPT, $response['errmsg'] ?? ''];
        }
        return [HTTP_SUCCESS, $response['url_link'] ?? ''];
    }

    public function generate_scheme($link = null,$link_day=30)
    {
        if (empty($link)) {
            global $user;
            $url_link = request()->post('url_link', '');
            $day = $post['day'] ?? 1;
            $day = $day < 0 ? 30 : ($day > 30 ? 30 : $day); //范围只能在1-30天
            $url_info = parse_url($url_link);
            $query = [
                "mall_id={$user->mall_id}"
            ];
            if (isset($url_info['query'])) {
                $arr = array_values(explode("&", $url_info['query']));
                $query = array_merge($query, $arr);
            }
            $query = implode("&", $query);
        } else {
            $query = $link->path ?? '';
            $url_info['path'] = $link->wx_url_path ?? '';
            $day = $link_day;
            global $user;
            $user = $link;
        }
        $data = [
            "jump_wxa" => [
                "path" => str_replace("..", 'pages', $url_info['path'] ?? ''),
                'query' => $query
            ],
            'expire_time' => strtotime("+{$day} day", time()),

        ];

        $response = UrlLink::generate_scheme($data);

        if ($response['errcode'] != 0) {
            return [HTTP_NOTACCEPT, $response['errmsg'] ?? ''];
        }
        return [HTTP_SUCCESS, $response['openlink'] ?? ''];
    }
}